import lexer.Reader;
import lexer.Scanner;
import parser.Parser;

import java.io.*;

public class Compiler {

    public static void main(final String[] args) throws IOException {
        if (args.length < 2) {
            System.err.println("Wrong number of input.");
            System.exit(-1);
        }

        compile(new File(args[0]), new File(args[1]));
    }

    private static void compile(final File input, final File output) throws IOException {
        System.out.println("Compiling... " + input.getName());
        try {
            final Reader reader = new Reader(input);
            final Scanner scanner = new Scanner(reader);
            final Parser parser = new Parser(scanner);

            final boolean succ = parser.parse();

            if (succ) {

                try (final BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {
                    writer.write(parser.getCode());
                    System.out.println("Compiling successfully finished!");
                } catch (final IOException e) {
                    System.out.println("\tCould not write generated code.");
                }
            } else {
                System.out.println("The program is invalid!");
                System.out.println("\t" + parser.getError());
            }
        } catch (final FileNotFoundException e) {
            System.err.println("Couldn't find the input file.");
        }
    }
}
